import SocketServer as socketserver
import json
import time
import mysql.connector

class MyTCPHandler(socketserver.BaseRequestHandler):
    """
    Handler base on Online documentation of socketserver
    """

    def handle(self):
        # self.request is the TCP socket connected to the client
        self.data = self.request.recv(1024).strip()
        print("{} wrote:".format(self.client_address[0]))
        indata=self.data
        bjson=True
        try:
          test=json.loads(indata)
        except:
	  bjson=False
	else:
          if "payload" in test:
            datatime=int(1000*time.time())
            if "time" in test:
              datatime=int(test['time'])
            datasource=self.client_address[0]
            if "device" in test:
              datasource=test['device'].translate(' ./:;*|')
            multi=1
            if "mult" in test:
              multi=int(test['mult'])
            mycursor=mydb.cursor()
            payload=test['payload']
            for x,y in payload.items():
              # remove unwanted characters from variable name
              varx=x.translate(' ./:;*!')
              varx=varx[:64]
              value=0
              if "value" in y:
                value=y['value']
                sensor=""
                if "sensor" in y:
                  sensor=y['sensor']
                  sensor=sensor.translate(' ./:;*!')
                  sensor=sensor[:32]
                i2c=0
                if "i2c" in y:
                  i2c=int(y['i2c'])
                try:
                  mycursor.execute(sqlinsert.format(datatime,datasource,varx,sensor,i2c,int(multi*value)))
                except:
                  print("Error sql statement")
                  print(sqlinsert.format(datatime,datasource,varx,sensor,i2c,int(multi*value)))
              try:
                mydb.commit()
              except:
                print("Could not commit")
        # just send back the same data, but upper-cased
        self.request.sendall("Done")

if __name__ == "__main__":
    HOST, PORT = "", 24048
    pwf = open("my.cnf","r")
    pwj = json.loads(pwf.read())
    print(pwj)
    try:
      mydb=mysql.connector.connect(host="localhost",user=pwj['user'],passwd=pwj['password'],database=pwj['database'])
    except:
      print("Could not connect to sql server! Quitting")
    else:
      sqlinsert="insert into datain (time,device,var,sensor,i2c,value) values ({0:d},'{1:s}','{2:s}','{3:s}',{4:d},{5:d})"
    
    # Create the server, binding to localhost on port 9999
      server = socketserver.TCPServer((HOST, PORT), MyTCPHandler)

    # Activate the server; this will keep running until you
    # interrupt the program with Ctrl-C
      server.serve_forever()
